﻿using System;
using DDDProject.Aspects;
using DDDProjectSample.Domain.Infrastructure.Repositories;

namespace DDDProjectSample.Domain
{
    /// <summary>
    /// The MembersManager is responsible of users management tasks
    /// (authentication, member registration, member deletion, etc.)
    /// </summary>
    public class MembersManager
    {
        private static MembersManager _membersManager;

        [InjectComponent]
        private IMemberRepository _memberRepository;

        /// <summary>
        /// Creates a new instance of class MembersManager
        /// </summary>
        private MembersManager()
        {
        }

        /// <summary>
        /// Gets the MembersManager instance
        /// </summary>
        public static MembersManager Instance
        {
            get
            {
                if (_membersManager == null)
                {
                    lock (typeof(MembersManager))
                    {
                        if (_membersManager == null)
                        {
                            _membersManager = new MembersManager();
                        }
                    }
                }

                return _membersManager;
            }
        }

        /// <summary>
        /// Authenticate a member, based on supplied name and password
        /// </summary>
        /// <param name="name">The name of the member to authenticate</param>
        /// <param name="password">The password of the member to authenticate</param>
        /// <returns>The authenticated member, or null is the supplied credentials are not correct</returns>
        public Member Authenticate(string name, string password)
        {
            // Try to load the member
            Member member = _memberRepository.GetByLogin(name);

            // Verify credentials
            if (member != null && member.Password == password)
            {
                return member;
            }

            return null;
        }
    }
}
